# -*- python -*-
# ex: set syntax=python:

# This is a sample buildmaster config file. It must be installed as
# 'master.cfg' in your buildmaster's base directory (although the filename
# can be changed with the --basedir option to 'mktap buildbot master').

# It has one job: define a dictionary named BuildmasterConfig. This
# dictionary has a variety of keys to control different aspects of the
# buildmaster. They are documented in docs/config.xhtml .


# This is the dictionary that the buildmaster pays attention to. We also use
# a shorter alias to save typing.
c = BuildmasterConfig = {}

####### DB URL

# This specifies what database buildbot uses to store change and scheduler
# state
c['db_url'] = "sqlite:///state.sqlite"

####### BUILDSLAVES

# the 'slaves' list defines the set of allowable buildslaves. Each element is
# a BuildSlave object, which is created with bot-name, bot-password.  These
# correspond to values given to the buildslave's mktap invocation.
from buildbot.buildslave import BuildSlave
c['slaves'] = [ BuildSlave("linux_bot", "bot1passwd"),
                BuildSlave("python_bot", "pythonpasswd") ]

# to limit to two concurrent builds on a slave, use
#  c['slaves'] = [BuildSlave("bot1name", "bot1passwd", max_builds=2)]


# 'slavePortnum' defines the TCP port to listen on. This must match the value
# configured into the buildslaves (with their --master option)

c['slavePortnum'] = 9989

####### CHANGESOURCES

# the 'change_source' setting tells the buildmaster how it should find out
# about source code changes. Any class which implements IChangeSource can be
# put here: there are several in buildbot/changes/*.py to choose from.
#
#from buildbot.changes.pb import PBChangeSource
#c['change_source'] = PBChangeSource()

# For example, if you had CVSToys installed on your repository, and your
# CVSROOT/freshcfg file had an entry like this:
#pb = ConfigurationSet([
#    (None, None, None, PBService(userpass=('foo', 'bar'), port=4519)),
#    ])

# then you could use the following buildmaster Change Source to subscribe to
# the FreshCVS daemon and be notified on every commit:
#
#from buildbot.changes.freshcvs import FreshCVSSource
#fc_source = FreshCVSSource("cvs.example.com", 4519, "foo", "bar")
#c['change_source'] = fc_source

# or, use a PBChangeSource, and then have your repository's commit script run
# 'buildbot sendchange', or use contrib/svn_buildbot.py, or
# contrib/arch_buildbot.py :
#
#from buildbot.changes.pb import PBChangeSource
#c['change_source'] = PBChangeSource()

# If you wat to use SVNPoller, it might look something like
# Where to get source code changes
svnurl = "http://mipt-course.googlecode.com/svn/trunk"
python_svnurl = svnurl + "/pysandbox"

from buildbot.changes.svnpoller import SVNPoller
svn_poller = SVNPoller(
                   svnurl=svnurl,
                   project="mipt-course",
                   pollinterval=60, # seconds
                   histmax=10,
                   svnbin='/usr/bin/svn',
)

c['change_source'] = [ svn_poller ]

####### SCHEDULERS

## configure the Schedulers

from buildbot.scheduler import Scheduler
from buildbot.schedulers import timed

# Returns True if change affects files related to Python build.
def changeAffectsPython(change):
  for name in change.files:
    if name.startswith("pysandbox"):
      return True
  return False

# Returns True if change affects files related to C++ build.
def changeAffectsCPP(change):
  for name in change.files:
    if not name.startswith("pysandbox"):
      return True
  return False

c['schedulers'] = []
c['schedulers'].append(Scheduler(
                           name="cpp_scheduler",
                           branch=None,
                           treeStableTimer=60,
                           fileIsImportant=changeAffectsCPP,
                           builderNames=["linux-bot"]))
c['schedulers'].append(Scheduler(
                           name="python_scheduler",
                           branch=None,
                           treeStableTimer=60,
                           fileIsImportant=changeAffectsPython,
                           builderNames=["python-bot"]))
c['schedulers'].append(timed.Nightly(
                           name="nightly",
                           branch=None,
                           hour=3, minute=0,
                           onlyIfChanged=True,
                           builderNames=["linux-bot", "python-bot"]))

####### BUILDERS

# the 'builders' list defines the Builders. Each one is configured with a
# dictionary, using the following keys:
#  name (required): the name used to describe this builder
#  slavename or slavenames (required): which slave(s) to use (must appear in c['slaves'])
#  factory (required): a BuildFactory to define how the build is run
#  builddir (optional): which subdirectory to run the builder in

# buildbot/process/factory.py provides several BuildFactory classes you can
# start with, which implement build processes for common targets (GNU
# autoconf projects, CPAN perl modules, etc). The factory.BuildFactory is the
# base class, and is configured with a series of BuildSteps. When the build
# is run, the appropriate buildslave is told to execute each Step in turn.

# the first BuildStep is typically responsible for obtaining a copy of the
# sources. There are source-obtaining Steps in buildbot/steps/source.py for
# CVS, SVN, and others.

from buildbot.process import factory
from buildbot.steps.source import SVN
from buildbot.steps.shell import Compile
from buildbot.steps.shell import Configure
from buildbot.steps.shell import ShellCommand
from buildbot.steps.shell import Test
from buildbot.steps.python_twisted import Trial
linux_factory = factory.BuildFactory()
linux_factory.addStep(SVN(svnurl=svnurl, mode="update"))

# TODO(timurrrr): Avoid duplication of name=, description=, descriptionDone=.
# Looks like 'name' is used on the build page,
# 'description' is used on the waterfall view while the step is being executed,
# 'descriptionDone' is used after it has finished.

for build_type in ["Debug", "Release"]:
  linux_factory.addStep(
      ShellCommand( 
          # Will pass if the directory exists, thanks to -p.
          command=["mkdir", "-p", build_type],
          haltOnFailure=True,
          name="mkdir %s" % build_type,
          description="mkdir %s" % build_type,
          descriptionDone="mkdir %s" % build_type))
  linux_factory.addStep(
      Configure( 
          command=["cmake", "-DCMAKE_BUILD_TYPE=%s" % build_type, ".."],
          workdir="build/%s" % build_type,
          name="cmake for the '%s' build" % build_type,
          description="cmake for '%s'" % build_type,
          descriptionDone="cmake for '%s'" % build_type))
  linux_factory.addStep(
      Compile(
          command=["make", "build"],
          workdir="build/%s" % build_type,
          name="compile '%s'" % build_type,
          description="build '%s'" % build_type,
          descriptionDone="build '%s'" % build_type))
  linux_factory.addStep(
      Test(
          command=["make", "test"],
          workdir="build/%s" % build_type,
          name="run '%s' tests" % build_type,
          description="run '%s' tests" % build_type,
          descriptionDone="run '%s' tests" % build_type))
linux_factory.addStep(
    Test(
        command=["make", "USE_VALGRIND=1", "test"],
        workdir="build/Debug",
        name="run tests under Valgrind",
        description="valgrind",
        descriptionDone="valgrind"))

python_factory = factory.BuildFactory()
python_factory.addStep(SVN(svnurl = python_svnurl, mode="update"))
python_factory.addStep(
    Test(
        command=["make", "test"],
        name="run pysandbox/ tests",
        description="python tests",
        descriptionDone="python tests"))


from buildbot.config import BuilderConfig
linux_builder = BuilderConfig(
                  name="linux-bot",
                  slavename="linux_bot",
                  builddir="checkout",
                  factory=linux_factory)

python_builder = BuilderConfig(
                   name="python-bot",
                   slavename="python_bot",
                   builddir="python_checkout",
                   factory=python_factory)

c['builders'] = [linux_builder, python_builder]


####### STATUS TARGETS

# 'status' is a list of Status Targets. The results of each build will be
# pushed to these targets. buildbot/status/*.py has a variety to choose from,
# including web pages, email senders, and IRC bots.

c['status'] = []

from buildbot.status import html
from buildbot.status.web import auth, authz
authz_cfg=authz.Authz(
    # change any of these to True to enable; see the manual for more
    # options
    gracefulShutdown = False,
    forceBuild = False,
    forceAllBuilds = False,
    pingBuilder = False,
    stopBuild = False,
    stopAllBuilds = False,
    cancelPendingBuild = False,
)
c['status'].append(
    html.WebStatus(
        http_port=8080,
        authz=authz_cfg,
        revlink='http://code.google.com/p/mipt-course/source/detail?r=%s'
    )
)


from buildbot.status.mail import MailNotifier
import os

path = os.path.join(basedir, 'smtp_credentials.txt')
f = open(path, 'r')
smtp_user = f.readline().strip('\n')
smtp_passwd = f.readline().strip('\n')
f.close()

mn = MailNotifier(fromaddr=smtp_user,
                  # add @gmail.com if "@" is not in the commiter's ID
                  lookup="gmail.com",
                  extraRecipients=["timurrrr+gmc@gmail.com"],
                  subject="GMC buildbot %(result)s in %(builder)s",
                  sendToInterestedUsers=True,
                  useTls=True,
                  relayhost="smtp.gmail.com",
                  smtpPort=587,
                  smtpUser=smtp_user,
                  smtpPassword=smtp_passwd,
                  mode='failing')

c['status'].append(mn)


# from buildbot.status import mail
# c['status'].append(mail.MailNotifier(fromaddr="buildbot@localhost",
#                                      extraRecipients=["builds@example.com"],
#                                      sendToInterestedUsers=False))
#
# from buildbot.status import words
# c['status'].append(words.IRC(host="irc.example.com", nick="bb",
#                              channels=["#example"]))
# c['status'].append(words.IRC(host="irc.example.com", nick="bb",
#                              channels=["#example"], useSSL=True))
#
# from buildbot.status import client
# c['status'].append(client.PBListener(9988))


####### DEBUGGING OPTIONS

# if you set 'debugPassword', then you can connect to the buildmaster with
# the diagnostic tool in contrib/debugclient.py . From this tool, you can
# manually force builds and inject changes, which may be useful for testing
# your buildmaster without actually committing changes to your repository (or
# before you have a functioning 'sources' set up). The debug tool uses the
# same port number as the slaves do: 'slavePortnum'.

#c['debugPassword'] = "debugpassword"

# if you set 'manhole', you can ssh into the buildmaster and get an
# interactive python shell, which may be useful for debugging buildbot
# internals. It is probably only useful for buildbot developers. You can also
# use an authorized_keys file, or plain telnet.
#from buildbot import manhole
#c['manhole'] = manhole.PasswordManhole("tcp:9999:interface=127.0.0.1",
#                                       "admin", "password")


####### PROJECT IDENTITY

# the 'projectName' string will be used to describe the project that this
# buildbot is working on. For example, it is used as the title of the
# waterfall HTML page. The 'projectURL' string will be used to provide a link
# from buildbot HTML pages to your project's home page.

c['projectName'] = "mipt-course"
c['projectURL'] = "http://code.google.com/p/mipt-course/"

# the 'buildbotURL' string should point to the location where the buildbot's
# internal web server (usually the html.WebStatus page) is visible. This
# typically uses the port number set in the Waterfall 'status' entry, but
# with an externally-visible host name which the buildbot cannot figure out
# without some help.

c['buildbotURL'] = "http://tinyurl.com/mipt-course-buildbot-1/"
